﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ConfigController : BaseController
    {
        public ConfigController(ILogger<ConfigController> logger) : base(logger)
        {
        }

        /// <summary>
        /// 获取配置数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ReturnModel> Get(int id)
        {
            try
            {
                logger.LogInformation($"Config/Get:id={id}");
                ReturnModel returnModel = new ReturnModel();
                returnModel.Data = await DbHelper.Config.GetByIdAsync(id);
                returnModel.Count = returnModel.Data == null ? 0 : 1;
                return returnModel;
            }
            catch (Exception ex)
            {
                LogToDB("Config", "查询", $"参数：id={id}", "异常", $"{nameof(Get)}-{ex.Message}");
                return logger.ErrorModel(nameof(MonitorController) + "-" + nameof(Get), ex);
            }
        }

        /// <summary>
        /// 获取配置数据列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetList")]
        public async Task<ReturnModel> GetList()
        {
            try
            {
                var data = await DbHelper.Config.GetListAsync();
                return new ReturnModel { Count = data?.Count ?? 0, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Config", "查询", "参数：", "异常", $"{nameof(GetList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ConfigController)}/{nameof(GetList)}", ex);
            }
        }


        /// <summary>
        /// 更新配置数据
        /// </summary>
        /// <param name="model">更新实体</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ReturnModel> Update(Config model)
        {
            try
            {
                bool update = await DbHelper.Config.UpdateAsync(model);
                return new ReturnModel { Count = update ? 1 : 0 };
            }
            catch (Exception ex)
            {
                LogToDB("Config", "更新", "参数：", $"异常：{JsonConvert.SerializeObject(model)}", $"{nameof(Update)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ConfigController)}/{nameof(Update)}", ex);
            }
        }
    }
}
